package YS;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class WordDao {

	public boolean addWord(Word word) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "insert into t_word(english,chinese,baseid) values(?,?,?)";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setString(1, word.getEnglish());
		psmt.setString(2, word.getChinese());
		psmt.setInt(3, word.getBaseid());
		return psmt.executeUpdate() > 0;
	}

	public boolean updateWord(Word word) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "update t_word set english = ? ,set chinese = ? where wordid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setString(1, word.getEnglish());
		psmt.setString(2, word.getChinese());
		psmt.setInt(3, word.getWordid());
		return psmt.executeUpdate() > 0;
	}

	public boolean deleteWord(int wordid) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "delete from t_word where wordid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, wordid);
		return psmt.executeUpdate() > 0;

	}

	public Word getWord(int wordid) throws SQLException {

		Word w = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select wordid,english,chinese,baseid from t_word where wordid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, wordid);

		ResultSet rs = psmt.executeQuery();
		while (rs.next()) {
			w = new Word();
			w.setWordid(rs.getInt("wordid"));
			w.setEnglish(rs.getString("english"));
			w.setChinese(rs.getString("chinese"));
			w.setBaseid(rs.getInt("baseid"));
		}
		return w;
	}

	public List<Word> getWords(int baseid) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "select wordid,english,chinese,baseid from t_word where baseid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, baseid);
		ResultSet rs = psmt.executeQuery();
		List<Word> wordList = new ArrayList<Word>();
		Word w = null;
		while (rs.next()) { // 如果对象中有数据，就会循环打印出来
			w = new Word();
			w.setWordid(rs.getInt("wordid"));
			w.setEnglish(rs.getString("english"));
			w.setChinese(rs.getString("chinese"));
			w.setBaseid(rs.getInt("baseid"));
			wordList.add(w);
		}
		return wordList;
	}
}
